package com.lz.ccjdemo.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;


import com.google.gson.Gson;
import com.lz.ccjdemo.App;
import com.lz.ccjdemo.Config;
import com.lz.ccjdemo.R;
import com.lz.ccjdemo.base.BaseActivity;
import com.lz.ccjdemo.data.CodeData;
import com.lz.ccjdemo.http.HttpUtils;
import com.lz.ccjdemo.http.api.Api;
import com.lz.ccjdemo.http.data.BaseResultData;
import com.lz.ccjdemo.http.model.BaseModel;
import com.lz.ccjdemo.http.model.UserModel;
import com.lz.ccjdemo.http.subscriber.SimpleBaseSubscriber;
import com.lz.ccjdemo.utils.DataChangeUtils;
import com.lz.ccjdemo.utils.IntentUtils;
import com.lz.ccjdemo.utils.LoadingUtils;
import com.lz.ccjdemo.utils.PermissionsUtils;
import com.lz.ccjdemo.utils.UpdateAppUtils;
import com.lz.ccjdemo.utils.dialog.SimpleDialog;
import com.lz.ccjdemo.utils.file.FileHttpManager;
import com.lz.ccjdemo.utils.file.callback.IProgressListener;
import com.lz.ccjdemo.utils.file.down.DownUtils;
import com.lz.ccjdemo.utils.listener.PerfectClickListener;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MainActivity extends BaseActivity<BaseModel> implements View.OnClickListener {

    PermissionsUtils permissionsUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clickDataChange(View view) {
        startActivity(new Intent(this, DataChangeActivity.class));
        DataChangeUtils.getInstance().testDataUpdate();
    }

    public void clickToTts(View view){
        startActivity(new Intent(this, TtsActivity.class));
    }

    public void clickDynamicForms(View view) {
        startActivity(new Intent(this, DynamicFormsActivity.class));
    }

    public void clickFlowPathStyle(View view) {
        startActivity(new Intent(this, FlowPathStyleActivity.class));
    }

    public void clickListView(View view) {
        startActivity(new Intent(this, ListViewActivity.class));
    }

    public void clickTypeface(View view) {
        startActivity(new Intent(this, TypefaceActivity.class));
    }

    public void clickNetState(View view) {
        startActivity(new Intent(this, NetStateActivity.class));
    }

    public void clickSkeletonScreen(View view) {
        startActivity(new Intent(this, SkeletonScreenActivity.class));
    }

    public void clickFileWrite(View view) {
        //文件写入
//        if (permissionsUtils == null) {
//            permissionsUtils = new PermissionsUtils();
//        }

//        permissionsUtils.requestPermissions(this, new PermissionsUtils.OnResultListener() {
//            @Override
//            public void accept(boolean isSuccess) {
//                if (isSuccess) {
        writeFile();
//                } else {
//                    Toast.makeText(MainActivity.this, "权限获取失败", Toast.LENGTH_SHORT).show();
//                }
//            }
//        }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }

    private void writeFile() {
        FileOutputStream outputStream = null;
        try {
            String fileContents = "Hello,World!";
            outputStream = openFileOutput("tag.txt", Context.MODE_PRIVATE);
            outputStream.write(fileContents.getBytes());
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void clickGetLocation(View view) {
        if (permissionsUtils == null) {
            permissionsUtils = new PermissionsUtils();
        }
        permissionsUtils.requestPermissions(this, new PermissionsUtils.OnResultListener() {
            @Override
            public void accept(boolean isSuccess) {
                if (isSuccess) {
                    getLocation();
                } else {
                    Toast.makeText(MainActivity.this, "位置权限获取失败", Toast.LENGTH_SHORT).show();
                }
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);

    }

    private void getLocation() {
        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            @SuppressLint("MissingPermission") Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        if (bestLocation == null) {
            Toast.makeText(this, "位置信息获取失败", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "当前经纬度 Latitude=" + bestLocation.getLatitude()
                    + " Longitude=" + bestLocation.getLongitude(), Toast.LENGTH_SHORT).show();
        }
    }

    public void clickShowDialog(View view) {
        new SimpleDialog.Builder(this).setTitleStr("title")
//                .setCancelStr("cancel")
                .setConfirmStr("confirm")
                .setContextStr("context")
                .setDialogListener(new SimpleDialog.OnDefaultDialogListener() {
                    @Override
                    public void onCancel(AlertDialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onConfirm(AlertDialog dialog) {
                        dialog.dismiss();
                    }
                }).build();
    }

    public void clickHttpRequest(View view) throws UnsupportedEncodingException {
        Map<String, Object> getMap = new HashMap<>();
        getMap.put("code", "1");

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("code", "1234");
        String bodyData = new Gson().toJson(paramsMap);
        File file = new File("/image.jpg");
//        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), bodyData);
        HttpUtils.observe(HttpUtils.getDefault().get(Api.URL_TEXT, getMap))
                .subscribe(new SimpleBaseSubscriber<Object>() {
                    @Override
                    public void onSuccess(Object result) {
                        if (result != null) {
                            Gson gson = new Gson();
                            try {
                                CodeData data = gson.fromJson(gson.toJson(result), CodeData.class);
                                Toast.makeText(MainActivity.this, "result =" + new Gson().toJson(data), Toast.LENGTH_SHORT).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onFail(BaseResultData<Object> t) {
                        super.onFail(t);
                    }
                });
    }

    public void clickTimer(View view) {
        startActivity(new Intent(this, CirclePercentActivity.class));
    }

    private final int TAG_INTENT_CODE = 1001;

    public void clickIntentData(View view) {
        //如何需要带参数回来  content 必须是activity
        //传递的参数 只能是基础类型和序列化（Serializable）之后的对象
        IntentUtils.builder(this).addParam("tag_params", "我是MainActivity").startForResult(IntentDataActivity.class, TAG_INTENT_CODE);
    }

    public void clickExpandableListView(View view) {
        startActivity(new Intent(this, ExpandableListViewActivity.class));
    }

    public void clickLoading(View view) {
        LoadingUtils.showLoading(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                LoadingUtils.hideLoading();
            }
        }, 1000);
    }

    public void clickFixedBottom(View view) {
        startActivity(new Intent(this, FixedBottomActivity.class));
    }

    public void clickRecordingProcess(View view) {
        startActivity(new Intent(this, RecordingProcessActivity.class));
    }

    DownUtils downUtils;

    /**
     * 文件下载
     *
     * @param view
     */
    public void clickFileDown(View view) {
        if (permissionsUtils == null) {
            permissionsUtils = new PermissionsUtils();
        }
        permissionsUtils.requestPermissions(this, new PermissionsUtils.OnResultListener() {
            @Override
            public void accept(boolean isSuccess) {
                if (!isSuccess) return;
                LoadingUtils.showLoading(MainActivity.this);
                if (downUtils != null && downUtils.isRunning()) {
                    Toast.makeText(MainActivity.this, "文件正在下载中，请稍后……", Toast.LENGTH_SHORT).show();
                }
                String url = "https://pic.rmb.bdstatic.com/bjh/914b8c0f9814b14c5fedeec7ec6615df5813.jpeg";//要下载的文件路径
                String filePath = Environment.getExternalStorageDirectory() + "/Download/";//想要保存的路径
                String fileName = "img.jpeg";//想要保存的文件名字 要求带后缀（.png,.apk）
                downUtils = FileHttpManager.down(url, filePath, fileName);
                downUtils.registerProgressListener(new IProgressListener() {
                    @Override
                    public void onProgress(long progress, long totalProgress) {
                        Log.d("TAG", "Down Progress " + progress + " TotalProgress " + totalProgress);
                    }

                    @Override
                    public void onError(Exception e) {
                        LoadingUtils.hideLoading();
                        Toast.makeText(MainActivity.this, "下载失败 " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(String path) {
                        LoadingUtils.hideLoading();
                        Toast.makeText(MainActivity.this, "下载成功 " + filePath + fileName, Toast.LENGTH_SHORT).show();
                    }
                }).startDown(0);
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
    }


    /**
     * 显示更新弹窗 并更新安装
     *
     * @param view
     */
    public void clickUpdateApp(View view) {
        if (permissionsUtils == null) {
            permissionsUtils = new PermissionsUtils();
        }
        String version = "1.0.1";//新的版本号
        String title = "版本更新";//更新标题
        boolean isShowCancel = true;//是否显示取消 false 弹窗不可取消 必须升级
        String appUrl = "https://downapp.baidu.com/baidusearch/AndroidPhone/13.51.5.11.1/1/1037068k/20240223235929/baidusearch_AndroidPhone_13-51-5-11-1_1037068k.apk?responseContentDisposition=attachment%3Bfilename%3D%22baidusearch_AndroidPhone_1037068k.apk%22&responseContentType=application%2Fvnd.android.package-archive&request_id=1709264688_6707946257&type=static";//安装包下载地址
        UpdateAppUtils.getInstance().showAppUpdateDialog(this, version, title, isShowCancel
                , new UpdateAppUtils.DialogClickListener() {
                    @Override
                    public void onCancel(Dialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onConfirm(Dialog dialog) {
                        UpdateAppUtils.getInstance().updateApp(MainActivity.this, permissionsUtils, isShowCancel, appUrl);
                    }

                    @Override
                    public void onDismiss() {

                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        permissionsUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case TAG_INTENT_CODE:
                    //读取返回的数据  或者操作
                    if (data != null && data.hasExtra("tag")) {
                        String msg = "params：" + data.getStringExtra("tag");
                        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                        Log.d("TAG", msg);
                    }
                    break;
            }
        }
    }

    PerfectClickListener clickListener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(View v) {

        }
    };

    @Override
    public void onClick(View v) {
        clickListener.onClick(v);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //防止内存泄漏
        permissionsUtils = null;
    }
}
